package db

import (
	"io/ioutil"
	"ulcdkey/tool"
)

// 上传文件
func (this *File) UploadFile(b []byte, path, fileName string) (id, urlStr string, err error) {
	md5 := tool.Md5(b)
	path += md5 + "-" + fileName
	tx, err := db.Begin()
	if err != nil {
		return
	}
	defer tx.Commit()
	var n int

	err = tx.QueryRow("select count(1),ifnull(id,0),ifnull(path,'') from file where md5=?", md5).Scan(&n, &id, &urlStr)
	if err != nil {
		tx.Rollback()
		return
	}
	if n > 0 {
		return
	}
	urlStr = path
	_, err = tx.Exec("insert into file(name,md5,path) values(?,?,?)", fileName, md5, path)
	if err != nil {
		tx.Rollback()
		return
	}
	err = tx.QueryRow("select last_insert_id()").Scan(&id)
	if err != nil {
		tx.Rollback()
		return
	}

	err = ioutil.WriteFile("public"+path, b, 777)
	if err != nil {
		tx.Rollback()
		return
	}
	return
}
